package es.deusto.eside.programacion4.mario2d.states;

import java.io.IOException;
import java.net.URL;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import org.newdawn.slick.state.transition.FadeInTransition;
import org.newdawn.slick.state.transition.FadeOutTransition;

import TWLSlick.TWLInputAdapter;

import de.matthiasmann.twl.Button;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer;
import de.matthiasmann.twl.theme.ThemeManager;
import es.deusto.eside.programacion4.mario2d.Mario2D;

/**
 * Menu principal del juego
 * 
 * @author Sergio
 * 
 */
public class MainMenuState extends BasicGameState {
	/**
	 * Widget padre
	 */
	private Widget root;

	/**
	 * LWGLRenderer contexto de renderizado
	 */
	private LWJGLRenderer lwjglRenderer;
	/**
	 * theme tema usado para la escritura
	 */
	private Object theme;

	/**
	 * gui intefaz de usuario
	 */
	private GUI gui;
	/**
	 * twlInputoAdapter: gestiona las entradas de los botones
	 */
	private TWLInputAdapter twlInputAdapter;

	/**
	 * buttonInitGame: boton de inicio
	 */
	private Button buttonInitGame;
	/**
	 * Boton de opciones
	 */
	private Button buttonOptions;
	/**
	 * Boton ranking
	 */
	private Button buttonRanking;
	/**
	 * fpsFont: fuente para escribir
	 */
	private UnicodeFont fpsFont;
	/**
	 * Ruta de la fuente
	 */
	final String fontPath = "resources/ttf/mario.ttf";
	/**
	 * Numero de estado
	 */
	private int stateId;
	/**
	 * temporizador para pasar estado
	 */
	int timer = 10;
	/**
	 * Imagen de fondo
	 */
	public Image background;

	int second = 0;

	/**
	 * Constructor
	 * 
	 * @param id
	 */
	public MainMenuState(int id) {
		this.stateId = id;
	}

	@Override
	public void init(GameContainer gc, StateBasedGame sb) throws SlickException {
		initGUI(gc, sb);
		background = new Image("resources/Images/Menu/back.jpg");
		background = background.getScaledCopy(640, 480);
		fpsFont = new UnicodeFont(fontPath, 40, true, false);
		fpsFont.addAsciiGlyphs();
		fpsFont.addGlyphs(400, 600);
		fpsFont.getEffects().add(new ColorEffect(java.awt.Color.WHITE));
		fpsFont.loadGlyphs();

	}

	@Override
	public void render(GameContainer arg0, StateBasedGame arg1, Graphics g)
			throws SlickException {
		background.draw();
		twlInputAdapter.render();

	}

	@Override
	public void update(GameContainer arg0, StateBasedGame sb, int delta)
			throws SlickException {
		Mario2D.lifes = 3;
		Mario2D.points = 0;
	}

	/**
	 * Inicializa los botones del juego
	 * 
	 * @param sb
	 *            : maneja el estado del juego
	 */
	private void initButtonsEvent(final StateBasedGame sb) {
		buttonInitGame.addCallback(new Runnable() {
			@Override
			public void run() {
				sb.enterState(GameState.FIRST_LEVEL.ordinal());
			}
		});
		buttonOptions.addCallback(new Runnable() {

			@Override
			public void run() {
				sb.enterState(GameState.OPTION_STATE.ordinal());
			}
		});
		buttonRanking.addCallback(new Runnable() {

			@Override
			public void run() {
				sb.enterState(GameState.RANKING_MENU.ordinal());
			}
		});

	}

	/**
	 * Crea los botones de opciones
	 */
	private void createButtons() {
		buttonInitGame = new Button();
		buttonInitGame.setText(("start"));
		buttonInitGame.setTheme("button");
		buttonInitGame.setPosition(50, 50);

		twlInputAdapter.getGui().getRootPane()
				.setSize(Mario2D.WIDTH, Mario2D.HEIGHT);
		twlInputAdapter.getGui().getRootPane().add(buttonInitGame);
		buttonInitGame.adjustSize();

		buttonOptions = new Button();
		buttonOptions.setText(("Settings"));
		buttonOptions.setTheme("button");
		buttonOptions.setPosition(50, 100 + buttonInitGame.getHeight());

		twlInputAdapter.getGui().getRootPane()
				.setSize(Mario2D.WIDTH, Mario2D.HEIGHT);
		twlInputAdapter.getGui().getRootPane().add(buttonOptions);
		buttonOptions.adjustSize();

		buttonRanking = new Button();
		buttonRanking.setText(("Ranking"));
		buttonRanking.setTheme("button");
		buttonRanking.setPosition(50, 150 + 2 * buttonOptions.getHeight());

		twlInputAdapter.getGui().getRootPane()
				.setSize(Mario2D.WIDTH, Mario2D.HEIGHT);
		twlInputAdapter.getGui().getRootPane().add(buttonRanking);
		buttonRanking.adjustSize();

	}

	/**
	 * Inicializa el tema de escritura
	 * 
	 * @param gc
	 *            : ventana del juego
	 */
	private void initTWL(GameContainer gc) {
		root = new Widget();
		root.setTheme("");

		// save Slick's GL state while loading the theme
		GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
		try {
			lwjglRenderer = new LWJGLRenderer();
			theme = ThemeManager.createThemeManager(new URL(
					"file:resources/theme/LuffySurvivalTheme.xml"),
					lwjglRenderer);
			gui = new GUI(root, lwjglRenderer);
			gui.applyTheme((ThemeManager) theme);
		} catch (LWJGLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// restore Slick's GL state
			GL11.glPopAttrib();
		}

	}

	/**
	 * 
	 * @param gc
	 *            : ventana del juego
	 * @param sb
	 *            : lleva el control de los estados del juego
	 */
	private void initGUI(final GameContainer gc, final StateBasedGame sb) {
		initTWL(gc);
		twlInputAdapter = new TWLInputAdapter(gui, gc.getInput());

		createButtons();
		initButtonsEvent(sb);
	}

	@Override
	public int getID() {
		return stateId;
	}

	@Override
	public void enter(final GameContainer gameContainer, final StateBasedGame sb) {
		gameContainer.getInput().addPrimaryListener(twlInputAdapter);
		if (Mario2D.p.isMusic() == true) {
			Mario2D.menu.loop();
		}
		if (Mario2D.p.isFullScreen() == true) {
			try {
				gameContainer.setFullscreen(true);
			} catch (SlickException e) {
				e.printStackTrace();
			}
		} else {
			try {
				gameContainer.setFullscreen(false);
			} catch (SlickException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void leave(final GameContainer gameContainer, final StateBasedGame sb) {
		gameContainer.getInput().removeListener(twlInputAdapter);
		Mario2D.menu.stop();
	}

}
